package com.awonsome.core.result;

import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Data;

import java.io.Serializable;
import java.util.Objects;

/**
 * @author yangdejun
 * @date 2022/1/11 15:12
 */
@Data
@JsonInclude(value = JsonInclude.Include.NON_NULL)
public class Result<T> implements Serializable {

    private String code;

    private T data;

    private String msg;

    private Integer total;

    public static <T> Result<T> success() {
        return success(null);
    }

    public static <T> Result<T> success(T data) {
        ResultCode resultCode = ResultCode.SUCCESS;
        if (data instanceof Boolean && Boolean.FALSE.equals(data)) {
            resultCode = ResultCode.SYSTEM_EXECUTION_ERROR;
        }
        return result(resultCode, data);
    }

    public static <T> Result<T> success(T data, Long total) {
        Result<T> result = new Result<>();
        result.setCode(ResultCode.SUCCESS.getCode());
        result.setMsg(ResultCode.SUCCESS.getMsg());
        result.setData(data);
        result.setTotal(total.intValue());
        return result;
    }

    private static <T> Result<T> result(String code, String msg, T data) {
        Result<T> result = new Result<>();
        result.setCode(code);
        result.setData(data);
        result.setMsg(msg);
        return result;
    }

    private static <T> Result<T> result(IResultCode resultCode, T data) {
        return result(resultCode.getCode(), resultCode.getMsg(), data);
    }

    /**
     * 验证结果是否成功
     * @param result
     * @return
     */
    public static boolean isSuccess(Result<?> result) {
        return Objects.nonNull(result) && ResultCode.SUCCESS.getCode().equals(result.getCode());
    }
}
